package com.taobao.diamond.manager.impl;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.cookie.CookieSpec;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.IOException;
import java.util.List;

/**
 * <p></p>
 * User: <a href="mailto:yanmingming1989@163.com">严明明</a>
 * Date: 15/7/23
 * Time: 下午4:08
 */
public class HttpSimpleClient {

    private static final Log logger = LogFactory.getLog(HttpSimpleClient.class);


    public static HttpResult httpGet(String ip, String url, List<NameValuePair> params, String encoding, long readTimeoutMs) throws IOException {
        HttpClient httpClient = new HttpClient();
        Cookie[] cookies = null;
        int statusCode = 0;

        String LOGIN_DIAMOND_URL = buildLoginUrl(ip);
        GetMethod getMethod = new GetMethod(LOGIN_DIAMOND_URL);
        PostMethod postMethod = new PostMethod(LOGIN_DIAMOND_URL);
        try {
            int status = httpClient.executeMethod(postMethod);
            CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
            cookies = cookiespec.match(ip, 8080, "/", false, httpClient.getState().getCookies());

            if (params != null) {
                for (NameValuePair nameValuePair : params) {
                    url = url + "&" + nameValuePair.getName() + "=" + nameValuePair.getValue();
                }
            }
            getMethod = new GetMethod(url);
            getMethod.setRequestHeader("Cookie", cookieToString(cookies));
            getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, encoding);
            statusCode = httpClient.executeMethod(getMethod);

            if (statusCode == HttpStatus.SC_OK) {
                HttpResult httpResult = new HttpResult(statusCode, getMethod.getResponseBodyAsString());
                return httpResult;
            }
        } catch (Exception e) {
            logger.error("Exception: " + e.toString());
        } finally {
            getMethod.releaseConnection();
        }
        return new HttpResult(statusCode, "");
    }

    public static HttpResult httpPost(String ip, String url, List<NameValuePair> params, String encoding, long readTimeoutMs) throws IOException {
        HttpClient httpClient = new HttpClient();
        Cookie[] cookies = null;
        int statusCode = 0;

        String LOGIN_DIAMOND_URL = buildLoginUrl(ip);
        PostMethod postMethod = new PostMethod(LOGIN_DIAMOND_URL);
        try {
            int status = httpClient.executeMethod(postMethod);
            CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
            cookies = cookiespec.match(ip, 8080, "/", false, httpClient.getState().getCookies());
            postMethod = new PostMethod(url);
            postMethod.setRequestHeader("Cookie", cookieToString(cookies));
            postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, encoding);
            postMethod.setRequestBody(params.toArray(new org.apache.commons.httpclient.NameValuePair[params.size()]));
            statusCode = httpClient.executeMethod(postMethod);

            if (statusCode == HttpStatus.SC_OK) {
                HttpResult httpResult = new HttpResult(statusCode, postMethod.getResponseBodyAsString());
                return httpResult;
            }
        } catch (Exception e) {
            logger.error("Exception: " + e.toString());
        } finally {
            postMethod.releaseConnection();
        }
        return new HttpResult(statusCode, "");
    }


    private static String buildLoginUrl(String ip) {
        return "http://" + ip.trim() + ":8080/login.do?method=login&username=" + ServerLadpConfig.DEFAULT_LOGIN_DIAMOND_USERNAME + "&password=" + ServerLadpConfig.DEFAULT_LOGIN_DIAMOND_PASSWORD;
    }

    public static class HttpResult {
        public final int code;
        public final String content;

        public HttpResult(int code, String content) {
            this.code = code;
            this.content = content;
        }
    }


    public static String cookieToString(Cookie[] cookie) {
        StringBuffer cookieBuf = new StringBuffer(256);
        for (Cookie tmpCookie : cookie) {
            cookieBuf.append(tmpCookie).append(";");
        }
        return cookieBuf.toString();
    }

}
